<template>
    <div class="task-manage page-container">
      <el-form class="query-form"
        ref="queryForm"
        :model="queryParams"
        :inline="true"
        size="small"
        label-width="">
        <el-form-item class="big-query" label="关键词"
          prop="keyword">
          <el-input v-model="queryParams.keyword"
            placeholder="请输入关键词"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
            @clear="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
            size="small"
            @click="handleQuery">搜索</el-button>
          <el-button size="small"
            @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operate-wrap">
        <el-button type="primary" @click.stop="openTaskDialog()"  size="small" icon="el-icon-plus">新增</el-button>
      </div>
      <el-table v-loading="loading" :data="taskList">
        <el-table-column label="任务ID"  width="300" prop="task_id" />
        <el-table-column label="任务名称" prop="name" />
        <el-table-column label="任务类型" width="160" prop="type">
          <template slot-scope="scope">
           <span>{{getCurrentTaskType(scope.row.type)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="任务图标" width="200">
          <template slot-scope="scope">
            <el-image slot="reference"
              style="height: 36px;cursor: pointer;"
              :src="scope.row.icon"
              fit="contain"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="任务权重" min-width="200" prop="weight"/>
        <el-table-column label="状态" min-width="120" prop="status">
          <template slot-scope="scope">
           <span>{{getCurrentTaskStatus(scope.row.status)}}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="300">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" @click.stop="updateTaskStatus(scope.row, 'draf')">上架</el-button> -->
            <el-button type="text" size="small" v-if="scope.row.status !== 'published'" @click.stop="updateTaskStatus(scope.row, 'published')">发布</el-button>
            <el-button type="text" size="small" @click.stop="openTaskDialog(scope.row)">修改</el-button>
            <el-button type="text" size="small" @click.stop="updateTaskStatus(scope.row,'deleted')">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-wrap">
        <pagination v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.page_size"
        @pagination="getTableList" />
      </div>
      <el-dialog
        class="add-task-dialog"
        :title="form.task_id ? '编辑任务配置':'新增任务配置'"
        :visible.sync="dialogVisible"
        width="600px"
        :close-on-click-modal="false"
        @closed="reset">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="任务ID" prop="task_id">
            <el-input v-model="form.task_id" readonly></el-input>
          </el-form-item>
          <el-form-item label="任务名称" prop="name">
            <el-input v-model.trim="form.name" :maxLength="30"></el-input>
          </el-form-item>
          <el-form-item label="最多参加" prop="max_join">
            <el-input-number v-model="form.max_join" :step="1" :min="1" step-strictly></el-input-number><span class="unit">次</span>
          </el-form-item>
          <el-form-item label="任务类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择任务类型">
              <el-option v-for="(value,key) in taskTypes" :key="key" :label="value" :value="key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="获得奖励">
            <el-row :gutter="12" v-for="(item,index) in form.cfg.reward" :key="index">
              <el-col :span="8" style="padding-left: 0 !important;">
                <el-select v-model="item.pkg_id" placeholder="请选择奖励">
                  <el-option v-for="pkg in pkgList" :label="pkg.name" :value="pkg.pkg_id" :key="pkg.pkg_id"></el-option>
                </el-select>
              </el-col>
              <el-col :span="6">
                <el-input-number v-model="item.duration" :step="1" :min="1"></el-input-number>
              </el-col>
              <el-col :span="3">
                天
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="任务图标" prop="icon">
            <ImgUpload v-model="form.icon"/>
          </el-form-item>
          <el-form-item label="任务权重" prop="weight">
            <el-input-number v-model="form.weight" :step="1" :min="1" :max="100" step-strictly></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addTask">确 定</el-button>
          <el-button @click="dialogVisible = false">取 消</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<script>
import ImgUpload from '@/components/img-upload'
import { listRightPackage } from '@/api/rights/package'
import { addTask, getTaskList, updateTask } from '@/api/task'
export default {
  data () {
    return {
      pkgList: [],
      queryParams: {
        page: 1,
        page_size: 10,
        keyword: ''
      },
      taskTypes: {
        'invite-new': '邀请新用户',
        'invitee': '领取新人礼'
      },
      statusDict: {
        'draf': '上架',
        'published': '发布',
        'deleted': '删除',
        'draft': '草稿'
      },
      total: 0,
      taskList: [],
      currentPage: 1,
      dialogVisible: false,
      loading: false,
      form: {
        task_id: '',
        name: '',
        type: 'invite-new',
        max_join: 1,
        cfg: {
          reward: [
            // {
            //   type: 'right_pkg',
            //   duration: 10
            // }
          ]
        },
        icon: '',
        weight: 10
      },
      rules: {
        // task_id: [
        //   { required: true, message: '请填写任务id', trigger: 'change' }
        // ],
        name: [
          { required: true, message: '请填写任务名称', trigger: 'change' }
        ],
        max_join: [
          { required: true, message: '请填写次数', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        icon: [
          { required: true, message: '请选择任务图标', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    ImgUpload
  },
  computed: {
    getCurrentTaskType () {
      return (type) => {
        return this.taskTypes[type] || ''
      }
    },
    getCurrentTaskStatus () {
      return (status) => {
        return this.statusDict[status] || ''
      }
    }
  },
  methods: {
    getPackageRightList () {
      listRightPackage({ page: 1, page_size: 100, status: 1 }).then(res => {
        this.pkgList = res.data.list || []
      })
    },
    openTaskDialog (row) {
      if (row) {
        const { cfg, ...other } = row
        const { max_join, reward } = JSON.parse(cfg)
        reward.forEach(item => { item.duration = Number(item.duration) / 24 / 60 })
        this.form = Object.assign(this.form, {
          ...other,
          max_join,
          cfg: { reward }
        })
      } else {
        this.form.cfg.reward = [{
          type: 'right_pkg',
          duration: 10,
          pkg_id: this.pkgList.length ? this.pkgList[0].package_id : ''
        }]
      }
      this.dialogVisible = true
    },
    // 获取列表数据
    getTableList () {
      this.loading = true
      getTaskList(this.queryParams).then(res => {
        this.taskList = res.data.list
        this.total = res.data.count || 0
      }).finally(() => {
        this.loading = false
      })
    },
    // 点击搜索
    handleQuery () {
      this.queryParams.page = 1
      this.getTableList()
    },
    // 重置
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增任务
    addTask () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const { max_join, cfg, ...param } = this.form
          const newCfg = { ...cfg, ...{ max_join } }
          newCfg.reward.forEach(item => { item.duration = Number(item.duration) * 24 * 60 })
          const requestParam = {
            ...param,
            ...{
              cfg: JSON.stringify(newCfg)
            }
          }
          const apiHandle = this.form.task_id ? updateTask : addTask
          apiHandle(requestParam).then(res => {
            this.msgSuccess(this.form.task_id ? '修改配置成功' : '新增配置成功')
            this.dialogVisible = false
            this.getTableList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    updateTaskStatus (row, status) {
      const id = row.id
      const { page: pageIndex, page_size: pageSize } = this.queryParams
      const operateName = this.statusDict[status]
      const isDelete = status === 'deleted'
      this.$confirm(`是否确认${operateName}该活动？活动名：${row.name}`, isDelete ? '警告' : '提示', {
        type: isDelete ? 'warning' : 'info'
      }).then(() => {
        updateTask({ id, status }).then(() => {
          this.queryParams.page = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getTableList()
          this.msgSuccess(`${operateName}成功`)
        })
      })
    },
    reset () {
      this.resetForm('form')
    }
  },
  created () {
    this.getPackageRightList()
    this.handleQuery()
  }
}
</script>
<style lang="scss" scoped>
.pagination-wrap {
  padding: 20px 0;
}
.add-task-dialog {
  .unit {
    margin-left: 10px;
  }
  .el-col {
    .el-input-number--medium {
      width: 100%;
    }
  }
}
</style>
